package com.gupt.weekly.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gupt.weekly.domain.Role;
import com.gupt.weekly.service.RoleService;
import com.gupt.weekly.vo.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * @author linzizun
 * @version 1.0
 * @date 2021/03/26 11:10
 */
@Slf4j
@RestController
@Api(tags = "角色模块接口")
@RequestMapping("/role")
public class RoleController {
    @Resource
    RoleService roleService;

    @ApiOperation(value = "创建角色", notes = "创建新的角色")
    @PostMapping(value = "/createRole")
    public CommonResult createRole(@Valid @RequestBody Role role) {
        role.setId(null);
        boolean result = roleService.save(role);
        if (result) {
            return new CommonResult(200, "插入数据库成功");
        } else {
            return new CommonResult(444, "插入数据库失败");
        }
    }

    @ApiOperation(value = "查询角色", notes = "根据id查询角色")
    @PostMapping(value = "/getRoleById")
    public CommonResult getRoleById(String id) {
        Role role = roleService.getById(id);
        if (null != role) {
            return new CommonResult(200, "查询数据库成功", role);
        } else {
            return new CommonResult(444, "查询数据库失败");
        }
    }

    @ApiOperation(value = "获取角色列表", notes = "获取角色列表")
    @GetMapping(value = "/getRoleList")
    public CommonResult getRoleList(@RequestBody Role role) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", role.getName())
                .or().like("details", role.getDetails())
                .or().eq("grade", role.getGrade())
                .or().eq("parent_id", role.getParent_id());
        List<Role> roleList = roleService.list(queryWrapper);
        if (roleList.size() > 0) {
            return new CommonResult(200, "查询数据库成功", roleList);
        } else {
            return new CommonResult(444, "数据库无相关记录");
        }
    }

    @ApiOperation(value = "更新角色", notes = "根据id更新角色")
    @PostMapping(value = "/updateRoleById")
    public CommonResult updateRoleById(@RequestBody Role role) {
        boolean result = roleService.updateById(role);
        if (result) {
            return new CommonResult(200, "更新数据库成功");
        } else {
            return new CommonResult(444, "更新数据库失败");
        }
    }
}
